
#include <stdio.h>
#include <iostream>

#include "jell/pool.hpp"

using namespace std;
using namespace jell;

void    showPoolStatus(Pool<char>& pool)
{
    cout << "pool capacity=" << pool.capacity()
         << " count=" << pool.count()
         << " used=" << pool.count_used()
         << " free=" << pool.count_free()
         << endl;
}

void    test_lease_release(Pool<char>& pool, size_t nblock)
{
    vector<char*>   tmp;
    for (size_t i=0; i<nblock; i++) {
        char*   p = pool.lease();
        tmp.push_back(p);
        if ( (i>0) && (0 == (i % 10000)) ) {
            cout << "\tleasing\t" << i << "/" << nblock << " ...\n";
        }
        //fprintf(stdout, "%p ", p);
        //showPoolStatus( pool );
    }
    showPoolStatus( pool );
    for (size_t i=0; i<tmp.size(); i++) {
        char*   p = tmp[i];
        pool.release( p );
        if ( (i>0) && (0 == (i % 10000)) ) {
            cout << "\treleasing\t" << i << "/" << tmp.size() << " ...\n";
        }
        //fprintf(stdout, "%p ", p);
        //showPoolStatus( pool );
    }
    tmp.clear();
    showPoolStatus( pool );
}

int     main( void )
{
    Pool<char>  pool(64);
    showPoolStatus( pool );

    test_lease_release(pool, 13701);
    test_lease_release(pool, 13701);
    test_lease_release(pool, 63701);
    test_lease_release(pool, 63701);
    test_lease_release(pool, 123701);
    test_lease_release(pool, 123701);
    test_lease_release(pool, pool.capacity());
    test_lease_release(pool, pool.capacity());
    test_lease_release(pool, 19);
    test_lease_release(pool, 199);
    test_lease_release(pool, 3701);
    test_lease_release(pool, 13701);
    test_lease_release(pool, 63701);
    test_lease_release(pool, 123701);
    test_lease_release(pool, pool.capacity());
    test_lease_release(pool, pool.capacity() + 1);  // would throw bad_alloc exception

    return  0;
}
